package uk.co.q3c.deplan.server.util.validation.rules;

import java.io.Serializable;

import javax.persistence.Id;

import uk.co.q3c.deplan.client.domain.AbstractDomainObject;
import uk.co.q3c.deplan.client.domain.DomainKind;
import uk.co.q3c.deplan.client.domain.DomainObject;
import uk.co.q3c.deplan.client.domain.resource.PersistenceReferenceException;
import uk.co.q3c.deplan.server.util.validation.ValidationResult;

import com.googlecode.objectify.Key;

/**
 * Integer must be in the range <code>min</code> to <code>max</code> inclusive
 * 
 * @author DSowerby 23 Apr 2009
 * 
 */
public class LongRange extends AbstractDomainObject implements Serializable, ValidationPropertyRule {
	private static final long serialVersionUID = 1L;
	@Id
	private Long keyId;
	private long min;
	private long max;

	public LongRange() {
		super();
	}

	public LongRange(long min, long max) {
		super();
		this.min = min;
		this.max = max;
	}

	public long getMin() {

		return min;
	}

	public void setMin(long min) {

		this.min = min;
	}

	public long getMax() {

		return max;
	}

	public void setMax(long max) {

		this.max = max;
	}

	/**
	 * 
	 * @see uk.co.q3c.deplan.util.validation.rules.ValidationPropertyRule#validate
	 */
	@Override
	public ValidationResult validate(String propertyName, Object propertyValue, ValidationResult vr) {
		vr.setValid(true);
		if (propertyValue instanceof Long) {

			long value = (Long) propertyValue;
			if (value < min) {
				vr.setValid(false);
				vr.addValidationMessage(propertyName + " cannot be less than " + new Long(min).toString());
			} else {
				if (value > max) {
					vr.setValid(false);
					vr.addValidationMessage(propertyName + " cannot be greater than " + new Long(max).toString());
				}
			}
		} else {
			vr.addValidationMessage("Invalid class for validation rule");
			vr.setValid(false);
			return vr;
		}
		return vr;
	}

	@Override
	public DomainKind getKind() {
		return DomainKind.Validation;
	}

	public Long getKeyId() {
		return keyId;
	}

	@Override
	public Key<? extends DomainObject> getKey() throws PersistenceReferenceException {
		throw new RuntimeException("Not yet implemented");
	}

	@Override
	public void setKeyId(Long keyId) {
		throw new RuntimeException("Not yet implemented");
	}

}
